<template>
  <div class="structure-tree">
    <header>
      <h2>组织架构</h2>
      <!-- <el-icon class="add" @click="deptEvent({ id: '0', deptName: '' }, 1)"><ele-CirclePlus /></el-icon> -->
    </header>
    <el-tree
      :data="treeData"
      :props="defaultProps"
      @node-click="nodeClick"
      default-expand-all
      :expand-on-click-node="false"
      draggable
      @node-drop="nodeDrop"
    >
      <template #default="{ node, data }">
        <span
          class="custom-tree-node"
          :class="{
            active: currentNode.id == data.id,
            'show-hide': data.parentId != '0'
          }"
        >
          <span v-if="node.label.length > 8" class="treeLabel">{{
            node.label
          }}</span>
          <span v-else>{{ node.label }}</span>
          <span
            class="operate"
            v-if="buttonDisplayOrNot(buttonCodes, 'zzAddDeptBtn')"
          >
            <a @click.stop="deptEvent(data, 1)" style="height: 26px">
              <span
                v-if="data.parentId == '0'"
                style="display: flex; align-items: center"
                ><el-icon><ele-Plus /></el-icon>部门</span
              ><span v-else
                ><el-icon><ele-Plus /></el-icon
              ></span>
            </a>
            <a
              style="margin-left: 8px"
              @click.stop="deptEvent(data, 2)"
              v-if="data.parentId != '0'"
            >
              <el-icon><ele-Edit /></el-icon>
            </a>
            <el-popconfirm
              width="150"
              confirm-button-text="删除"
              cancel-button-text="取消"
              :icon="InfoFilled"
              icon-color="#FC770A"
              title="确定删除？"
              @confirm="deleteEvent(data)"
              v-if="data.parentId != '0'"
            >
              <template #reference>
                <a style="margin-left: 8px">
                  <el-icon><ele-Delete /></el-icon>
                </a>
              </template>
            </el-popconfirm>
          </span>
        </span>
      </template>
    </el-tree>
    <DeptDialog
      :myDialog="deptDia"
      :node="node"
      :type="type"
      @flash="flash"
    ></DeptDialog>
  </div>
</template>

<script lang="ts" setup>
import { InfoFilled } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import {
  ref,
  watch,
  reactive,
  onMounted,
  defineAsyncComponent,
  onBeforeUnmount
} from 'vue'
import emitter from '/@/utils/mitt'
import { getTree, deleteDept } from '/@/api/setting/structure'
import { buttonDisplayOrNot } from '../../../utils/buttonBoolean'
import {
  updateParentIdAndSortApi,
  getButtonListByRoleApi
} from '/@/api/publicApi'
import { Session } from '/@/utils/storage'
const menu = Session.get('menu')
const buttonCodes = ref<any>([])
const DeptDialog = defineAsyncComponent(
  () => import('/@/views/setting/components/DeptDialog.vue')
)

interface Tree {
  deptName: string
  parentName: string
  id: string
  parentId: string
  children?: Tree[]
}
const defaultProps = {
  children: 'children',
  label: 'deptName'
}

let treeData: Tree[] = ref([])
let [deptDia, node, type, currentNode] = [
  ref<boolean>(false),
  ref({}),
  ref(1),
  ref({})
]

// 递归，求树第一个子项，用于第一次进页面默认选中
const getDepth = (obj: any) => {
  let cur = {}
  if (obj[0].children && obj[0].children.length) {
    cur = getDepth(obj[0].children)
  } else {
    cur = obj[0]
  }
  return cur
}

const getTreeList = async () => {
  let res = await getTree()
  if (res.code == 0) {
    treeData.value = res.data
    if (treeData.value.length) {
      currentNode.value = treeData.value[0]
      emitter.emit('deptCurrentNode', currentNode.value)
    }
  }
}
onMounted(() => {
  getTreeList()
  menu.forEach(async (element: any) => {
    if (element.menuUrl == '/setting/Structure') {
      let res = await getButtonListByRoleApi({
        terminalType: 1,
        menuPid: element.id
      })
      res.data.forEach((item: any) => {
        buttonCodes.value.push(item.buttonCode)
      })
    }
  })
})

const num = ref('')

const nodeClick = (data: Tree) => {
  currentNode.value = data
  emitter.emit('deptCurrentNode', currentNode.value)
}

emitter.on('tableListNum', (n: any) => {
  num.value = n
})

const flash = () => {
  getTreeList()
}

const deleteEvent = async (node: Tree) => {
  let res = await deleteDept({ id: node.id })
  if (res.code == 0) {
    ElMessage.success('删除成功！')
    flash()
  }
}

const deptEvent = (data: any, t: number) => {
  node.value = data
  type.value = t
  deptDia.value = !deptDia.value
}

const nodeDrop = (node1: any, node2: any, wz: any, event: any) => {
  console.log(node1, node2)
  let params = {
    id: node1.data.id,
    parentId: node2.data.id,
    sort: 1
  }
  updateParentIdAndSortApi(params).then((res) => {
    if (res.code == 0) {
      ElMessage.success('移动成功')
      getTreeList()
    }
  })
}

onBeforeUnmount(() => {
  emitter.off('tableListNum')
})
</script>

<style scoped lang="scss">
.structure-tree {
  header {
    display: flex;
    justify-content: space-between;
    height: 40px;

    h2 {
      font-size: var(--next-font-size16);
    }

    .add {
      font-size: var(--next-font-size18);
      color: var(--el-color-primary);
      margin-right: 8px;
      cursor: pointer;
    }
  }
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: var(--el-font-size-base);
  padding-right: 8px;
}

.show-hide :nth-child(2) {
  display: none;
}

.show-hide:hover :nth-child(2) {
  display: inline-block !important;
}

.operate {
  a {
    color: var(--el-color-primary);
  }
}

.active {
  color: var(--el-color-primary);
}

.treeLabel {
  width: 100px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
